const {
  baseURL
} = require('../config/api');
const {
  getToken,
  clearAll
} = require('./strorage')

let isLogin = 0;
const getStatus = (data) => {
  return (data || {}).code || ''
};

const showLoginOut = (callback) => {
  callback() 
}

const goLogin = () => {
  clearAll()
  const pages = getCurrentPages();
  getApp().closeLoading();
  if (!pages.length) {
    wx.nextTick(() => {
      wx.reLaunch({
        url: '/login/login',
        success: () => {
          isLogin = 0
        }
      })
    })
    return;
  };
  const parentPages = pages[pages.length - 1]
  const options = parentPages.options;
  const fromRoute = parentPages.route;

  const routeData = {
    fromRoute,
    options
  }
  wx.reLaunch({
    url: '/login/login?fromRouteData=' + JSON.stringify(routeData),
    success: () => {
      isLogin = 0
    }
  })
}

const checkState = (data) => {
  return data && data.success
}

const checkToken = (header) => {
  const token = getToken() || ''
  header.Authorization = 'bearer ' + token
}

export const _request = (options) => {
  const {
    baseUrl,
    url,
    params = {},
    method = 'POST',
    deleteToken
  } = options;
  const header = {
    'Content-type': 'application/x-www-form-urlencoded'
  };
  checkToken(header)
  if (deleteToken) {
    header.Authorization = ''
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl || baseURL}${url}`,
      data: params,
      header,
      method,
      success: (response) => {
        const statusCode = response.statusCode;
        if (statusCode === 200) {
          const resData = response.data;
          const status = getStatus(resData)
          // 判断token是否失效，跳转到登录页
          if (status === 50014) {
            // 这个字段是用来控制跳到登录页次数的，当页面中同时有多个接口调用时，避免重复跳到登录页，加一下限制
            isLogin++
            if (isLogin === 1) {
              showLoginOut(goLogin)
            }
          } else if (checkState(resData)) {
            const data = resData.data;

            if (data) {
              resolve(data);
            } else {
              resolve();
            }
          } else {
            resData && getApp().showToast(resData.message)
            reject(resData || 'error');
          }
        } else {
          getApp().showToast(response.message)
          reject(response);
        }
      },
      fail: (error) => {
        console.log(error)
        reject(error);
      }
    });
  });
};

export const _uploadFile = (options) => {
  const {
    baseUrl,
    url,
    params = {},
    formData,
    deleteToken
  } = options;
  const header = {
    'content-type': 'multipart/form-data'
  };
  checkToken(header)
  if (deleteToken) {
    header.Authorization = ''
  }
  return new Promise((resolve, reject) => {
    const {
      filePath,
      name = 'file'
    } = params;
    wx.uploadFile({
      url: `${baseUrl || baseURL}${url}`,
      filePath,
      formData,
      name,
      header,
      success(response) {
        const statusCode = response.statusCode;
        if (statusCode === 200) {
          const resData = JSON.parse(response.data);

          if (checkState(resData)) {
            const data = resData.data;

            if (data) {
              resolve(data);
            } else {
              resolve();
            }
          } else {
            reject(resData);
          }
        } else {
          reject(response);
        }
      },
      fail(error) {
        reject(error);
      }
    });
  });
};